#!/bin/bash

function usage 
{
	echo -e "Wrong number of parameters!"
	echo -e "Usage:"
	echo -e "	create_module <module name> <package> [signature]"
	echo -e "	- <module name>: Name of the module that will be created."
	echo -e "	- <package>: Package where the module will be created."
	echo -e "	- optional: [signature]: A file that contains the signature to be placed in generated files."
	echo -e ""
	echo -e "	Example:"
	echo -e "		create_module my_module my.module.package ~/my_signature.txt"

	exit 1
}

# $1 path; $2 text
function add_import
{
	if [ -e "${1}/__init__.py" ]
	then
		count=`grep -c -w "${2}" "${1}/__init__.py"`

		if [ $count -eq 0 ]
		then
			line=`grep -n -m 1 -w "import" "${1}/__init__.py" | cut -f1 -d:`

			if [ -n "${line}" ]
			then
				sed -i "${line}i${2}" "${1}/__init__.py"
			else
				echo "${2}" >> "${1}/__init__.py"
			fi
		fi
	fi	
}

if [ $# -lt 2 ]
then
	usage
fi

signature=""

if [ $# -eq 3 ]
then
	text=`cat $3`
	signature="\n${text}\n"
fi

path="."
header="\"\"\"\nGenerated by <Python Project Utils>\nVisit the project in http://code.google.com/p/python-project-utils/\n${signature}\"\"\"\n"
class_name=""

for folder in $(echo -e $2 | tr "." "\n")
do
	parent_path=$path
	path="${path}/${folder}"

	if [ ! -d $path ]
	then
		mkdir $path
	fi

	if [ ! -e "${path}/__init__.py" ]
	then
		echo -e "${header}" > "${path}/__init__.py"
	fi
done

for name_token in $(echo -e $1 | tr "_" "\n")
do
	class_name="${class_name}${name_token^}"
done

if [ ! -e "${path}/${1}.py" ]
then
	echo -e "${header}" > "${path}/${1}.py"
	echo -e "class ${class_name}(object):\n\tpass" >> "${path}/${1}.py"
fi

if [ $1 != "__main__" ]
then
	add_import $path "from ${1} import *"
fi
